var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session=require("express-session")

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var menuRouter = require('./routes/menu');

var app = express();

/* 后台开允许跨域 */
app.all('*', (req, res, next) => {
    const { origin, Origin, referer, Referer } = req.headers;
    const allowOrigin = origin || Origin || referer || Referer || '*';
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
      res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("Access-Control-Allow-Credentials", true); //可以带cookies
      res.header("X-Powered-By", 'Express');
      if (req.method == 'OPTIONS') {
        res.sendStatus(200);
      } else {
      next();
      }
  });

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
/* session的中间件 */
app.use(session({
  secret: "keyfor xinga",  //session签名
  resave: true, //强制保存 session 即使它并没有变化,。默认为 true。建议设置成 false。 don't save session if unmodified
  saveUninitialized:true  //强制将未初始化的 session 存储。当新建了一个 session 且未设定属性或值时，它就处于
}))

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/menu', menuRouter);

module.exports = app;
